package org.example.configcenter;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.Ordered;
import org.springframework.boot.logging.DeferredLog;
import org.springframework.core.annotation.Order;

import java.util.HashMap;
import java.util.Map;

// 使用@Order控制执行顺序（可选）
@Order(Ordered.HIGHEST_PRECEDENCE + 10) // 确保在默认配置加载前执行
public class ConfigCenterEnvironmentPostProcessor implements EnvironmentPostProcessor {

    private final DeferredLog logger = new DeferredLog();

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment,
                                       SpringApplication application) {
        // 1. 检查是否启用配置中心（从现有环境变量中读取）
        boolean enabled = environment.getProperty("config.center.enabled", Boolean.class, true);
        if (!enabled) {
            logger.debug("Config center is disabled");
            return;
        }

        // 2. 伪代码：从配置中心拉取配置（实际实现取决于你的配置中心）
        Map<String, Object> remoteConfigs = fetchFromConfigCenter(environment);

        // 3. 将配置添加到环境变量最前面（高优先级）
        MapPropertySource propertySource = new MapPropertySource("config-center", remoteConfigs);
        environment.getPropertySources().addFirst(propertySource);

        logger.info("Loaded " + remoteConfigs.size() + " configurations from config center");
    }

    // 伪代码：从配置中心获取配置
    private Map<String, Object> fetchFromConfigCenter(ConfigurableEnvironment env) {
        Map<String, Object> configs = new HashMap<>();

        // 伪实现 - 实际应该调用配置中心客户端API
        String serverAddr = env.getProperty("config.center.server-addr");
        String namespace = env.getProperty("config.center.namespace");

        logger.info("Connecting to config center at " + serverAddr + "...");

        // 模拟获取配置
        configs.put("database.url", "jdbc:mysql://remote-host:3306/db");
        configs.put("database.username", "remote_user");
        configs.put("database.password", "remote_pass123");

        return configs;
    }
}